package org.ljy.lotterysystem.controller;

import org.ljy.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import org.ljy.lotterysystem.common.exception.ControllerException;
import org.ljy.lotterysystem.common.pojo.CommonResult;
import org.ljy.lotterysystem.common.utils.JacksonUtil;
import org.ljy.lotterysystem.controller.param.CreateActivityParam;
import org.ljy.lotterysystem.controller.param.PageParam;
import org.ljy.lotterysystem.controller.result.CreateActivityResult;
import org.ljy.lotterysystem.controller.result.FindActivityDetailResult;
import org.ljy.lotterysystem.controller.result.FindActivityListResult;
import org.ljy.lotterysystem.service.IActivityService;
import org.ljy.lotterysystem.service.dto.*;
import org.ljy.lotterysystem.service.impl.ActivityServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.stream.Collectors;

@RestController
public class ActivityController {

    @Autowired
    private IActivityService activityService;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * 1.创建活动
     * @param param
     * @return
     */
    @RequestMapping("/activity/create")
    public CommonResult<CreateActivityResult> createActivity(
            @Validated @RequestBody CreateActivityParam param) {

        logger.info("ActivityController, createActivity, param: {}", JacksonUtil.writeValueAsString(param));
        return CommonResult.success(convertToCreateActivityResult(activityService.createActivity(param)));
    }

    private CreateActivityResult convertToCreateActivityResult(CreateActivityDTO activity) {
        if(null == activity) {
            throw new ControllerException(ControllerErrorCodeConstants.ACTIVITY_CREATE_ERROR);
        }
        CreateActivityResult result = new CreateActivityResult();
        result.setActivityId(activity.getActivityId());
        return result;
    }


    /**
     * 2.获取活动(简介)列表页
     * @param param
     * @return
     */
    @RequestMapping("/activity/find-list")
    public CommonResult<FindActivityListResult> findActivityList(PageParam param) {
        logger.info("ActivityController, findActivityList, param: {}", JacksonUtil.writeValueAsString(param));
        return CommonResult.success(
                convertToFindActivityListResult(
                        activityService.findActivityList(param)
                ));
    }

    private FindActivityListResult convertToFindActivityListResult(PageListDTO<ActivityDTO> activityList) {
        if(null == activityList) {
            logger.error("ActivityController, convertToFindActivityListResult, activityList is null");
            throw new ControllerException(ControllerErrorCodeConstants.ACTIVITY_LIST_ERROR);
        }
        FindActivityListResult result = new FindActivityListResult();
        result.setTotal(activityList.getTotal());//总数
        result.setRecords(activityList.getData()
                .stream()
                .map(
                        activityDTO -> {
                            FindActivityListResult.ActivityInfo activityInfo = new FindActivityListResult.ActivityInfo();
                            activityInfo.setActivityId(activityDTO.getActivityId());
                            activityInfo.setActivityName(activityDTO.getActivityName());
                            activityInfo.setDescription(activityDTO.getDescription());
                            activityInfo.setValid(activityDTO.valid());
                            return activityInfo;
                        }
                ).collect(Collectors.toList()));
        return result;
    }

    /**
     * 3.查询完整的活动信息
     * @param activityId
     * @return
     */
    @RequestMapping("/activity-detail/find")
    public CommonResult<FindActivityDetailResult> findActivityDetail(Long activityId) {
        logger.info("ActivityController, findActivityDetail, activityId: {}", activityId);
        ActivityDetailDTO detailDTO = activityService.getActivityDetail(activityId);
        return CommonResult.success(convertToFindActivityDetailResult(detailDTO));
    }

    private FindActivityDetailResult convertToFindActivityDetailResult(ActivityDetailDTO detailDTO) {
        if(null == detailDTO) {
            logger.error("ActivityController, convertToFindActivityDetailResult, detailDTO is null");
            throw new ControllerException(ControllerErrorCodeConstants.ACTIVITY_DETAIL_ERROR);
        }
        FindActivityDetailResult result = new FindActivityDetailResult();
        //1.存入活动信息
        result.setActivityId(detailDTO.getActivityId());
        result.setActivityName(detailDTO.getActivityName());
        result.setDescription(detailDTO.getDesc());
        result.setValid(detailDTO.valid());
        //2.奖品信息 (按照奖品等级排序：1,2,3)
        result.setPrizes(detailDTO
                .getPrizeDTOList()
                .stream()
                .sorted(Comparator.comparingInt(PrizeDTO -> PrizeDTO.getTiers().getCode()))//按照奖品等级排序
                .map(prizeDTO -> {
                    FindActivityDetailResult.Prize prize = new FindActivityDetailResult.Prize();
                    prize.setPrizeId(prizeDTO.getPrizeId());
                    prize.setName(prizeDTO.getName());
                    prize.setImageUrl(prizeDTO.getImageUrl());
                    prize.setPrice(prizeDTO.getPrice());
                    prize.setDescription(prizeDTO.getDescription());
                    prize.setPrizeTierName(prizeDTO.getTiers().getMessage());
                    prize.setPrizeAmount(prizeDTO.getPrizeAmount());
                    prize.setValid(prizeDTO.valid());
                    return prize;
                })
                .collect(Collectors.toList()));
        //3.人员信息
        result.setUsers(detailDTO
                .getUserDTOList()
                .stream()
                .map(userDTO -> {
                    FindActivityDetailResult.User user = new FindActivityDetailResult.User();
                    user.setUserId(userDTO.getUserId());
                    user.setUserName(userDTO.getUserName());
                    user.setValid(userDTO.valid());
                    return user;
                })
                .collect(Collectors.toList()));
        return result;
    }






}
